import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:squat_easy/generated/assets.dart';
import 'package:squat_easy/se_route.dart';
import 'package:video_player/video_player.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

class SeVideoPlayerPage extends StatefulWidget {
  const SeVideoPlayerPage(this.filePath, {super.key});

  final String filePath;

  @override
  State<SeVideoPlayerPage> createState() => _SeVideoPlayerPageState();
}

class _SeVideoPlayerPageState extends State<SeVideoPlayerPage> {
  VideoPlayerController? _controller;
  bool _isPlaying = false;

  @override
  void initState() {
    super.initState();

    File file = File(widget.filePath);
    _controller = VideoPlayerController.file(file)
      ..initialize().then((_) {
        // 视频初始化完成后刷新状态
        setState(() {});
      })
      ..setLooping(true); // 设置循环播放
  }

  @override
  void dispose() {
    // 页面销毁时释放资源
    _controller?.dispose();
    super.dispose();
  }

  void _togglePlayPause() {
    setState(() {
      if (_controller?.value.isPlaying == true) {
        _controller?.pause();
        _isPlaying = false;
      } else {
        _controller?.play();
        _isPlaying = true;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      scaffoldBackgroundColor: Colors.black,
      child: _controller?.value.isInitialized == true
          ? Stack(
              children: [
                Center(
                  child: FractionallySizedBox(
                    widthFactor: 1,
                    child: AspectRatio(
                      aspectRatio: _controller!.value.aspectRatio,
                      child: _buildVideo(),
                    ),
                  ),
                ),
                if (!_isPlaying) _buildPlayBtn().center(),
                _buildBackBtn().positioned(left: 30, top: ScreenUtil().statusBarHeight),
              ],
            )
          : const Center(child: CircularProgressIndicator()),
    );
  }

  Widget _buildVideo() => ButtonWidget(
        onTap: _togglePlayPause,
        hasInkWell: false,
        child: VideoPlayer(_controller!),
      );

  Widget _buildPlayBtn() {
    return Container(
      decoration: CommonDecoration.getShapeDecoration(
        bg: Colors.black.withOpacity(0.5),
        radius: 60.w,
      ),
      alignment: Alignment.center,
      width: 60.w,
      height: 60.w,
      child: ButtonWidget.icon(
        IconWidget.icon(
          Icons.play_arrow,
          size: 40.w,
          color: Colors.white,
        ),
        hasInkWell: false,
        onTap: _togglePlayPause,
      ),
    );
  }

  Widget _buildBackBtn() {
    return ButtonWidget.icon(
      Assets.svgAppBarBack.toSvg(width: 40),
      onTap: () {
        _controller?.pause();
        SeRoute.close();
      },
      hasInkWell: false,
    );
  }
}
